
from sanic import Sanic
from sanic import response
from sanic_cors import CORS
from sanic.log import logger
from build_db import ExecuteSqlScript
from db_interface.add_user import AddUser
from db_interface.login import Login
from db_interface.verfiy_token import VerfiyToken
from db_interface.change_password import ChangePassword
from db_interface.add_duty import AddDuty
from db_interface.lift_duty import LiftDuty
from db_interface.select_users import SelectUsers
from db_interface import ConnPG
from db_interface import select_duty

app = Sanic(__name__)
CORS(app)

@app.listener('before_server_start')
async def setup_db(app, loop):
    #创建数据库，sql放在build_db文件夹下面
    ExecuteSqlScript().execute_all_script('build_db')

@app.listener('after_server_start')
async def start_db_pool(app, loop):
    ConnPG(loop=loop)
    logger.debug('Server PostgreSQL successfully started!')

@app.route("/")
async def test(request):
    return response.json({"hello": "world"})

#添加用户
@app.route("/add_user", methods=['POST'])
async def add_user(request):

    phone = request.form.get('phone')
    name = request.form.get('name')
    password = request.form.get('password')

    result = await AddUser().add_user(name, phone, password)

    return response.json(result)

#删除用户，用来添加用户时出现错误时删除，
@app.route("/del_user", methods=['POST'])
# @app.route("/del_user")
async def add_user(request):

    user_id = request.form.get('user_id')
    # user_id = request.args.get('user_id')

    result = await AddUser().del_user(user_id)

    return response.json(result)

#更新用户名
@app.route("/update_user", methods=['POST'])
# @app.route("/update_user")
async def update_user(request):

    user_id = request.form.get('user_id')
    new_name = request.form.get('new_name')
    # user_id = request.args.get('user_id')
    # new_name = request.args.get('new_name')

    result = await AddUser().update_user(user_id, new_name)

    return response.json(result)

#更新用户电话 未测试
@app.route("/update_phone", methods=['POST'])
# @app.route("/update_phone")
async def update_phone(request):

    user_id = request.form.get('user_id')
    phone = request.form.get('phone')
    # user_id = request.args.get('user_id')
    # phone = request.args.get('phone')

    result = await AddUser().update_phone(user_id, phone)

    return response.json(result)


#登录
@app.route('/login', methods=["POST"])
async def login(request):

    phone = request.form.get('phone')
    # name = request.form.get('name')
    password = request.form.get('password')

    result = await Login().login(phone, password)

    return response.json(result)

#登录状态验证，token值验证
@app.route('/verfiy_token', methods=["POST"])
async def verfiy_token(request):

    user_id = request.form.get('user_id')
    # name = request.form.get('name')
    token = request.form.get('token')

    result = await VerfiyToken().verify_token(user_id, token)

    return response.json(result)

#修改密码
@app.route('/change_password', methods=["POST"])
async def change_password(request):

    phone = request.form.get('phone')
    new_pwd = request.form.get('new_pwd')
    old_pwd = request.form.get('old_pwd')

    result = await ChangePassword().change_password(phone, old_pwd, new_pwd)

    return response.json(result)


#添加职务
@app.route('/add_duty', methods=["POST"])
async def add_duty(request):

    duty = request.form.get('duty')

    result = await AddDuty().add_duty(duty)

    return response.json(result)


#删除用户，用来添加用户时出现错误时删除，
@app.route("/del_duty", methods=['POST'])
# @app.route("/del_duty")
async def del_duty(request):

    duty_id = request.form.get('duty_id')
    # duty_id = request.args.get('duty_id')

    result = await AddDuty().del_duty(duty_id)

    return response.json(result)

#更新用户名
@app.route("/update_duty", methods=['POST'])
# @app.route("/update_duty")
async def update_duty(request):

    duty_id = request.form.get('duty_id')
    new_name = request.form.get('new_name')
    # duty_id = request.args.get('duty_id')
    # new_name = request.args.get('new_name')

    result = await AddDuty().update_duty(duty_id, new_name)

    return response.json(result)





#用户添加职务
@app.route('/user_add_duty', methods=["POST"])
async def user_add_duty(request):

    user_id = request.form.get('user_id')
    duty_id = request.form.get('duty_id')

    result = await AddDuty().user_add_duty(user_id, duty_id)

    return response.json(result)

#解除用户职务
@app.route('/user_lift_duty', methods=["POST"])
async def user_lift_duty(request):

    user_id = request.form.get('user_id')
    duty_id = request.form.get('duty_id')

    result = await LiftDuty().user_lift_duty(user_id, duty_id)

    return response.json(result)

#查询所有的职务
@app.route('/select_all_duty')
async def select_all_duty(request):

    result = await select_duty.SelectDuty().select_all_duty()

    return response.json(result)

#查询职务下有哪些人 测试在test_user_add_duty.py下
@app.route('/select_user_by_duty')
async def select_user_by_duty(request):

    duty_id = request.args.get('duty_id')

    result = await select_duty.SelectDuty().select_user_by_duty(duty_id)

    return response.json(result)


@app.route('/select_duty_by_user_id')
async def select_duty_by_user_id(request):

    user_id = request.args.get('user_id')

    result = await select_duty.SelectDuty().select_duty_by_user_id(user_id)

    return response.json(result)


#展示所有用信息
@app.route('/show_all_user', methods=["GET"])
async def show_all_user(request):

    page = request.args.get('page')
    limit = request.args.get('limit')
    if page == None:
        page = '1'
    if limit == None:
        limit = '20'
    result = await SelectUsers().select_all_users(page, limit)

    return response.json(result)

@app.route('/show_all_user_by_users_table', methods=["GET"])
async def show_all_user_by_users_table(request):

    page = request.args.get('page')
    limit = request.args.get('limit')
    if page == None:
        page = '1'
    if limit == None:
        limit = '20'
    result = await SelectUsers().select_all_users_by_users_table(page, limit)

    return response.json(result)

#用户信息接口 可传不同参数来获取对应的用户信息
@app.route('/user_info', methods=["GET"])
async def user_info(request):

    user_id = request.args.get('user_id')

    phone = request.args.get('phone')

    duty = request.args.get('duty')

    name = request.args.get('name')

    if user_id != None:

        result = await SelectUsers().select_user_id_info(user_id)
    
    elif phone != None:

        result = await SelectUsers().select_user_phone_info(phone)
    
    elif duty != None:

        result = await SelectUsers().select_user_duty_info(duty)

    elif name != None:

        result = await SelectUsers().select_user_name_info(name)

    else:

        result = {
            'status': -1,
            'errorCode': 105100,
            'errorMsg': '请检查参数，需要一个必传参数',
            'resultBody': None
        }

    return response.json(result)

if __name__ == "__main__":

    app.run(host="0.0.0.0", port=8000, debug=True)
